package ru.compft.web.validator;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import ru.compft.common.utils.GlobalErrors;
import ru.compft.web.beans.PasswordBean;

import javax.annotation.Resource;

/**
 * User: ASUS
 * Date: 09.08.12
 * Time: 21:00
 * Валидатор для формы смена пароля
 */
@Component("сhangePasswordBeanValidator")
public class ChangePasswordBeanValidator implements Validator {

    public static final String PASSWORD = "password";
    public static final String CONFIRM_PASSWORD = "confirmPassword";
    private static final int MINIMUM_PASSWORD_LENGTH = 6;

    @Resource(name = "messageSource")
    private MessageSource messageSource;

    @Override
    public boolean supports(Class<?> clazz) {
        return PasswordBean.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        // Локализованное название поля password
        final String localizedPassword = messageSource.getMessage(PASSWORD, null, LocaleContextHolder.getLocale());
        // Локализованное название поля confirmPassword
        final String localizedConfirmPassword = messageSource.getMessage(CONFIRM_PASSWORD, null, LocaleContextHolder.getLocale());

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, PASSWORD, GlobalErrors.FIELD_REQUIRED, new String[]{localizedPassword});
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, CONFIRM_PASSWORD, GlobalErrors.FIELD_REQUIRED, new String[]{localizedConfirmPassword});

        PasswordBean formBean = (PasswordBean) target;
        // длинна пароля меньше чем допустимое количество символов
        final String password = formBean.getPassword();
        if (password != null
                && password.trim().length() < MINIMUM_PASSWORD_LENGTH) {
            errors.rejectValue(PASSWORD, GlobalErrors.FIELD_MIN_LENGTH,
                    new Object[]{localizedPassword, Integer.toString(MINIMUM_PASSWORD_LENGTH)},
                    null);
        }

        // пароли не одинаковы
        final String confirmPassword = formBean.getConfirmPassword();
        if (password != null
                && !password.trim().equals(confirmPassword)) {
            errors.rejectValue(PASSWORD, GlobalErrors.FIELDS_NOT_EQUALS);
        }
    }
}
